package com.ruben.simplestreamquery.config;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import io.github.vampireachao.stream.core.clazz.ClassHelper;
import io.github.vampireachao.stream.plugin.mybatisplus.engine.mapper.DynamicMapperHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author VampireAchao
 * @since 2022/10/6 11:42
 */
@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(List<InnerInterceptor> interceptors) {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        interceptors.forEach(mybatisPlusInterceptor::addInnerInterceptor);
        return mybatisPlusInterceptor;
    }

    /**
     * mybatis plus setting
     *
     * @return MybatisPlusPropertiesCustomizer
     */
    @Bean
    public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() {
        return properties -> {
            properties.setTypeAliasesPackage("com.ruben.simplestreamquery.entity");
            MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
            mybatisConfiguration.setJdbcTypeForNull(null);
            properties.setConfiguration(mybatisConfiguration);
            GlobalConfig globalConfig = GlobalConfigUtils.getGlobalConfig(mybatisConfiguration);
            GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
            dbConfig.setIdType(IdType.AUTO);
            // close mybatis-plus banner
            globalConfig.setBanner(false);
            properties.setGlobalConfig(globalConfig);
        };
    }

    @Bean
    public DynamicMapperHandler dynamicMapperHandler(SqlSessionFactory sqlSessionFactory) {
        return new DynamicMapperHandler(sqlSessionFactory, ClassHelper.scanClasses("com.ruben.simplestreamquery.pojo.po"));
    }


}
